package goods

import (
	"encoding/json"
	"fmt"
	"log"
	goods1 "shop/internal/models/goods"
)

// 商品属性值详情
type propertyValuesInfo struct {
	ID                int64
	PropertyID        int64
	PropertyValueName string
}

type GoodsInfo struct {
	Id          int64
	Title       string
	Point       int64
	Description string
	Img         []Img
}

type Img struct {
	Images string `json:"images"`
}

// 商品属性详细字段
type goodsPropertyInfo struct {
	ID                 int64
	PropertyName       string
	PropertyValueInfos []propertyValuesInfo
}

func GetInmages(img string) []string {
	var imageData []string
	//解析json格式图片
	fmt.Println("接受到图片::", img)
	err := json.Unmarshal([]byte(img), &imageData)
	if err != nil {
		log.Println("解析图片数据失败", err)
		return nil
	}
	if imageData == nil {
		imageData = []string{} // 如果解析失败，返回空切片
	}
	return imageData
}

func GetGoodsInfo(goodsId int) (*GoodsInfo, error) {
	goodsById, err := new(goods1.Goods).GoodsListById(int64(goodsId))
	if err != nil {
		return &GoodsInfo{}, err
	}

	propertyById, err := new(goods1.GoodsProperty).GoodsPropertyById(goodsId)
	if err != nil {
		return &GoodsInfo{}, err
	}

	var propertyIds []int64
	for _, v := range propertyById {
		propertyIds = append(propertyIds, int64(v.ID))
	}
	propertyValues, err := new(goods1.GoodsPropertyValue).GoodsPropertyPropertyIdList(propertyIds)
	if err != nil {
		return &GoodsInfo{}, err
	}

	var propertyValueMap []propertyValuesInfo
	var goodsProper []goodsPropertyInfo

	for _, v := range propertyValues {
		propertyValueMap = append(propertyValueMap, propertyValuesInfo{
			ID:                int64(v.ID),
			PropertyID:        v.PropertyId,
			PropertyValueName: v.Name,
		})

		goodsProper = append(goodsProper, goodsPropertyInfo{
			ID:                 int64(v.ID),
			PropertyName:       v.Name,
			PropertyValueInfos: propertyValueMap,
		})
	}

	getInmages := GetInmages(goodsById.Img)
	var img []Img
	for _, v := range getInmages {
		img = append(img, Img{Images: v})
	}

	info := &GoodsInfo{
		Id:          int64(goodsById.ID),
		Title:       goodsById.Title,
		Description: goodsById.Description,
		Img:         img,
	}
	return info, nil
}
